package svc.elib.analysis;

import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;

import org.apache.commons.math3.stat.correlation.SpearmansCorrelation;


import svc.elib.db.Author;
import svc.elib.db.Database;
import svc.elib.socnet.CentralityMetrics;
import svc.elib.socnet.ConnectedComponents;
import svc.elib.socnet.Net;
import svc.elib.socnet.SocConstructor;
import svc.elib.socnet.TrivialComponents;

public class CorrelationsPerComponent {

	private LinkedList<Net> components;
	
	private TrivialComponents tc;
	
	private CentralityMetrics cm;
	
	public CorrelationsPerComponent(Net net) {
		cm = new CentralityMetrics(net);
		cm.computeBetweeness(false);
		
		ConnectedComponents cn = new ConnectedComponents(net);
		cn.resolveComponents();
		components = cn.getComponents();
		
		tc = new TrivialComponents(net);
	}
	
	private double computeCorrelations(double[] seq1, double[] seq2) {
		SpearmansCorrelation sc = new SpearmansCorrelation();
		return sc.correlation(seq1, seq2);
	}
	
	public void doCorrelations() {
		for (int i = 0; i < components.size(); i++) {
			Net comp = components.get(i);
			if (tc.isTrivial2(comp))
				continue;
		
			int cs = comp.getNumAuthors();
			
			double seqPapers[] = new double[cs];
			double seqActivity[] = new double[cs];
			double seqDegree[] = new double[cs];
			double seqBet[] = new double[cs];
			double seqCC[] = new double[cs];
			
			int scnt = 0;
			
			Iterator<Author> ait = comp.getGraph().getVertices().iterator();
			while (ait.hasNext()) {
				Author a = ait.next();
				
				int numPapers = a.getNumPapers();
				int activity = a.getActivitySpan();
				int degree = comp.getGraph().degree(a);
				double bet = cm.getBetweenness(a.getName());
				double cc = comp.getCC(a);
				
				seqPapers[scnt] = numPapers;
				seqActivity[scnt] = activity;
				seqDegree[scnt] = degree;
				seqBet[scnt] = bet;
				seqCC[scnt] = cc;
				
				++scnt;
			}
			
			double papers_activity = computeCorrelations(seqPapers, seqActivity);
			double papers_degree = computeCorrelations(seqPapers, seqDegree);
			double papers_bet = computeCorrelations(seqPapers, seqBet);
			double activity_degree = computeCorrelations(seqActivity, seqDegree);
			double activity_bet = computeCorrelations(seqActivity, seqBet);
			double degree_bet = computeCorrelations(seqDegree, seqActivity);
			
			System.out.println(cs + "," + papers_activity + "," + papers_degree + "," + papers_bet + ","
					          + activity_degree + "," + activity_bet + "," + degree_bet);
		}
	}
	
	public static void main(String[] args) 
		throws IOException
	{
		Database db = new Database("eLibData.csv", 1932, 2011);
		SocConstructor soc = new SocConstructor(db);
		Net net = soc.getNet();
		net.printInfo();
		
		CorrelationsPerComponent cpc = new CorrelationsPerComponent(net);
		cpc.doCorrelations();
	}
	
}
